package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 报警过滤
     */
    @Override
    public void alertFilter() {
        //1.首先查询所有规则
        long count = this.count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count == 0) {
            return;
        }
        //2.查询所有设备上报的数据
        List deviceDataObjectList =  redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(deviceDataObjectList)){
            return;
        }
        //3.遍历数据进行解析
        List<DeviceData> deviceDatas = new ArrayList<>();
        //否则的话遍历数据进行解析
        deviceDataObjectList.forEach(deviceData -> {
            List<DeviceData> deviceDataList = JSONUtil.toList(deviceData.toString(), DeviceData.class);
            deviceDatas.addAll(deviceDataList);
        });
        //4.数据报警处理
        deviceDatas.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    /**
     * 报警过滤
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData) {
        //1.查询该产品物模型下的全部处于启用状态的设备规则
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId()));
        if (CollUtil.isEmpty(alertRuleList)){
            return;
        }
        //4.判断持续周期
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(deviceData, alertRule);


        });
    }

    /**
     * 设备数据处理
     * @param deviceData
     * @param alertRule
     */
    private void deviceDataAlarmHandle(DeviceData deviceData, AlertRule alertRule) {
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime deviceDatatime = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        if (deviceDatatime.isBefore(startTime)||deviceDatatime.isAfter(endTime)) {
            return;
        }
        //如果在时间周期内进行下一步

        //2.判断数据阈值
        //设置报警次数表达式
        String iotId = deviceData.getIotId();
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId()+":"+ alertRule.getId();
        Long value = alertRule.getValue();
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        int compare = NumberUtil.compare(dataValue, value);
        String operator = alertRule.getOperator();
        //不满足报警预支
        if ((operator.equals(">=")&&compare>=0)||(operator.equals("<")&&compare<=0)) {
            log.info("设备数据{}满足报警规则{}", deviceData, alertRule);
            //满足报警规则接着往下进行
        }else {
            log.info("设备数据{}不满足报警规则{}", deviceData, alertRule);
            //表示当前数据不满足报警规则 那么在此之前存储的连续报警次数进行清空
            redisTemplate.delete(aggCountKey);
            return;
        }
        //3.判断沉默周期-- 判断是否在沉默周期内 如果在沉默周期内则不进行报警  --来到当前位置表明数据满足报警规则需要报警
        //设置沉默周期的key
        String alertSilentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId()+":"+ alertRule.getId();
        Integer alertSilentPeriod = alertRule.getAlertSilentPeriod();
        //读取redis中沉默周期是否存在
        String silentData  = (String) redisTemplate.opsForValue().get(alertSilentKey);
        if (StringUtils.isNotEmpty(silentData)) {
            //表示当前数据在沉默周期内
            log.info("设备数据{}在沉默周期内", deviceData);
            return;
        }
        //走到当前位置表示不在沉默周期内 并且需要进行报警
        //先查询缓存中报警次数
        String aggCountData  = (String) redisTemplate.opsForValue().get(aggCountKey);
        int count = StringUtils.isEmpty(aggCountData) ? 1 : (Integer.parseInt(aggCountData) + 1);
        Integer duration = alertRule.getDuration();
        //判断报警次数是否等于持续周期
        if (ObjectUtil.notEqual(duration, count)) {
            //不想等，则更新redis中的报警次数
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(count));
            return;
        }
        //校验全部通过,报警
        redisTemplate.delete(aggCountKey);
        //添加沉默周期
        redisTemplate.opsForValue().set(alertSilentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //完善报警信息 -- 添加将报警信息发送到对应人的id
        List<Long> userIds = new ArrayList<>();
        //如果是老人异常数据
        if (alertRule.getAlertDataType().equals(0)){
            if (deviceData.getLocationType().equals(0)){
                //通过老人id查找到对应的护理员列表
                 userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceData.getLocationType().equals(1)&& deviceData.getPhysicalLocationType().equals(2)){
                //对于绑定床位的设备进行报警
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            //表示是设备异常需要通知维修人员id
           userIds = sysUserMapper.selectUserIdByRoleName("维修工");
        }
        //无论任何情况都需要通知超级管理员
        List<Long> list = sysUserMapper.selectUserIdByRoleName("超级管理员");
        //合并
        userIds.addAll(list);
        //去重
        ArrayList<Long> allUserIds = CollUtil.distinct(userIds);

        //保存报警数据到报警数据表中
        insertAlertData(allUserIds, alertRule, deviceData);
    }

    /**
     * 保存报警数据
     * @param allUserIds
     * @param alertRule
     * @param deviceData
     */
    private void insertAlertData(ArrayList<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        //设置报警原因 格式为:报警原因，格式：功能名称+运算符+阈值+持续周期+聚合周期
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(),
                alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        //设置状态 0：待处理，1：已处理
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            dbAlertData.setCreateTime(null);
            dbAlertData.setCreateBy(null);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(list);

        //websocket推送消息
        websocketNotity(list.get(0), alertRule,allUserIds);
    }

    private void websocketNotity(AlertData alertData, AlertRule alertRule, ArrayList<Long> allUserIds) {
        //属性拷贝-- 将需要提示的信息拷贝到vo中 在前端界面进行显示
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);

    }
}
